<template>
  <div class="main-box">
    <div class="table-box">
      <div class="card select-box">
        <SelectFilter :data="selectFilterData" :default-values="selectFilterValues" @change="changeSelectFilter" />
      </div>
      <ProTable ref="pTable" :columns="columns" :init-param="initParam" :request-api="getDownloadWorkerVoListApi">
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" @click="handleOutput(scope.selectedListIds)"> 导出工友 </el-button>
        </template>
        <template #avator="scope">
          <div class="left-box">
            <img :src="getAvatorUrl(scope.row.workerAvator)" alt="用户头像" />
          </div>
          <el-badge is-dot class="marker-dot" :type="scope.row.flagIdentity == 'Y' ? 'success' : 'danger'">&nbsp;</el-badge>
        </template>
        <template #workerPhone="scope">
          <el-tag class="ml-2" size="small">{{ scope.row.workerPhone }}</el-tag>
        </template>
        <template #name="scope">
          <div class="work-info-wrapper" @click="handleOpenDialog(OptEnum.EDIT, scope.row)">
            <div class="right-box">
              <div class="info-item">
                <span class="info-info info-b">{{ scope.row.workerName }}</span>
                <el-tag v-if="scope.row.flagIdentity == 'Y'" class="ml-2" type="success" size="small">已认证</el-tag>
                <el-tag v-else class="ml-2" type="danger" size="small">未认证</el-tag>
                <!-- <el-button
                  class="ml-2"
                  :icon="Edit"
                  circle
                  size="small"
                  @click="handleOpenDialog(OptEnum.EDIT, scope.row)"
                ></el-button> -->
              </div>
              <div class="info-item mt-10">
                <span class="info-info info-s">{{ filterEnum(scope.row.workerGender - 0, genderType) }} </span>|
                <span class="info-info info-s">{{ getAge(scope.row.workerBirthday) }}&nbsp;岁</span>|
                <span class="info-info info-s">{{ scope.row.eduContent }} </span>|
                <span class="info-info info-s">{{ scope.row.workYearContent }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #flagSee="scope">
          <div class="flagsee-wrapper" @click="handleOpenDialog(OptEnum.EDIT, scope.row)">
            <!-- <div class="info-item">
              <el-tag v-if="scope.row.cpyBuy"> 下载 </el-tag>
              <el-tag v-else> 主动申请 </el-tag>
            </div> -->
            <div class="info-item">
              <span class="info-s" v-if="scope.row.cpyBuy">{{ scope.row.cpyBuy }}</span>
              <span class="info-s" v-else>{{ scope.row.applyJob }}</span>
            </div>
          </div>
        </template>
        <template #jobTitle="scope">
          <div class="apply-wrapper">
            <div class="job-title">
              {{ scope.row.jobTitle }}
            </div>
            <div class="job-date">
              <span class="job-data-title">申请时间：</span>
              <span class="job-data-info">{{ scope.row.applyDate }}</span>
            </div>
          </div>
        </template>
        <template #expJob="scope">
          <div class="expjob-wrapper" @click="handleOpenDialog(OptEnum.EDIT, scope.row)">
            <div class="info-item">
              <span class="info-b">{{ scope.row.expCity }}</span>
            </div>
            <div class="info-item">
              <el-tag v-for="(tag, idx) in getTags(scope.row.expJobTypeNames)" :key="idx">
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </template>
        <template #workContent="scope">
          <div class="work-tag-wrapper" @click="handleOpenDialog(OptEnum.EDIT, scope.row)">
            <div class="tag-bar">
              <el-tag v-for="(tag, idx) in getTags(scope.row.stags)" :key="idx">
                {{ tag }}
              </el-tag>
            </div>
            <div class="tag-bar">
              <el-tag v-for="(tag, idx) in getTags(scope.row.ftags)" :key="idx">
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </template>
        <template #expSalary="scope">
          <span>{{ scope.row.expSalaryStart }}&nbsp;-&nbsp;</span>
          <span>{{ scope.row.expSalaryEnd }}&nbsp;元&nbsp;</span>
        </template>
        <template #lastLoginDate="scope">
          {{ dateStr(scope.row.lastLoginDate) }}
        </template>
        <template #operation="scope">
          <el-button type="primary" @click.stop="handleOpenWorkGroupDialog(OptEnum.CREATE, scope.row.workerId)">分组</el-button>
          <el-button type="primary" @click.stop="handleOpenWorkMarkerDialog(OptEnum.EDIT, scope.row.workerId)">标记</el-button>
          <el-button plain @click="handleOutputOneWorker(scope.row.workerId)">导出</el-button>
          <!-- <el-button plain disabled>分享</el-button> -->
          <el-button type="primary" :icon="ChatDotRound" @click="handleChat(scope.row)"> 聊一聊 </el-button>
        </template>
      </ProTable>
      <WorkerDialog ref="dialogRef" @refresh-list="handleRefreshList" />
      <WorkerMarkerDialog ref="wmdialogRef" @refresh-list="handleRefreshList" />
      <WorkerGroupDialog ref="wgdialogRef" @refresh-list="handleRefreshList" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import WorkerDialog from "../components/WorkerDialog.vue";
import WorkerGroupDialog from "../components/WorkerGroup.vue";
import WorkerMarkerDialog from "../components/WorkerMarker.vue";
import { CirclePlus, ChatDotRound } from "@element-plus/icons-vue";
import { getDownloadWorkerVoListApi, exportCompanyWorkerApi, exportOneWorkerApi } from "@/api/modules/cpyswk/mgr";
import { ColumnProps } from "@/components/ProTable/interface";
// import { useHandleData } from "@/hooks/useHandleData";
import { OptEnum } from "@/biz/eenum/appEnum";
// import { CompanyWorkerVo } from "@/biz/interface/WorkerType";
import SelectFilter from "./components/SelectFilter.vue";
import { getAge, dateStr } from "@/utils";
import { filterEnum } from "@/utils";
import { genderType } from "@/biz/datas/sysData";
import defaultAvatar from "@/assets/images/davator.png";
import { getWorkerGroupsApi } from "@/api/modules/cpyswk/wk";
import { ElMessage } from "element-plus";
import { getUserDetails } from "@/api/modules/user";
import router from "@/routers";

const pTable = ref();
// 表格列配置
const columns: Partial<ColumnProps>[] = [
  { type: "selection", width: 60, fixed: "left" },
  // { type: "index", label: "#", width: 60 },
  {
    prop: "avator",
    label: "头像",
    width: 80
  },
  {
    prop: "flagSee",
    label: "下载时间",
    width: 100
  },
  {
    prop: "workerPhone",
    label: "联系电话",
    width: 120
  },
  {
    prop: "name",
    label: "工友信息"
  },
  {
    prop: "workContent",
    label: "工友标签"
  },
  {
    prop: "expJob",
    label: "期望岗位"
  },
  {
    prop: "expSalary",
    label: "期望薪资",
    width: 120
  },
  {
    prop: "lastLoginDate",
    label: "最近登录",
    width: 100
  },
  {
    prop: "operation",
    width: 360,
    fixed: "right",
    label: "操作"
  }
];
let selectFilterData = ref([
  {
    title: "工友分组",
    key: "groupId",
    options: []
  }
]);
// 默认 selectFilter 参数
const selectFilterValues = ref({});
// 固定在列表中的参数
const initParam = reactive({});
const changeSelectFilter = (val: any) => {
  // ElMessage.success("请注意查看请求参数变化 🤔");
  selectFilterValues.value = val;
  pTable.value.pageable.pageNum = 1;
  pTable.value.initParam.groupId = val.groupId;
  // console.log("参数的变化", selectFilterValues.value);
  // pTable.value.getTableList();
};

const getAvatorUrl = (aurl: string) => {
  let url = defaultAvatar;
  if (aurl) {
    url = aurl;
  }
  return url;
};

const getTags = computed(() => {
  return (tagsStr: string): string[] => {
    let tags: string[] = [];
    if (tagsStr && tagsStr.length) {
      tags = tagsStr.split(",");
    }
    return tags;
  };
});

// const markerType = computed(() => (mtype: number) => {
//   if (mtype) {
//     if (mtype == 1) {
//       return "success";
//     } else if (mtype == 2) {
//       return "warning";
//     } else if (mtype == 3) {
//       return "danger";
//     } else if (mtype == 4) {
//       return "info";
//     }
//   }
//   return "primary";
// });

//刷新数据列表
const handleRefreshList = () => {
  //刷新一下分组列表
  getCompanyGrups();
  pTable.value.getTableList();
};

const getCompanyGrups = async () => {
  selectFilterData.value[0].options = [];
  let { data } = await getWorkerGroupsApi({});
  if (data) {
    data.forEach(item => {
      selectFilterData.value[0].options.push({
        label: item.label,
        value: item.value,
        icon: item.icon
      });
    });

    console.log(selectFilterData);
  }
};

// 导出工友
const handleOutput = async (ids: string[]) => {
  // console.log(ids);

  if (ids && ids.length > 0) {
    const res = await exportCompanyWorkerApi({ cpywkIds: ids });
    if (res) {
      let fileName = "workers.xlsx"; // 文件名
      let blob = new Blob([res], {
        type: "application/vnd.ms-excel"
      });
      console.log("blobblobblob", blob);
      let elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.target = "_blank";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL对象
      document.body.removeChild(elink);
    }
  } else {
    ElMessage.error("请选择要导出的工友");
  }
};

const handleOutputOneWorker = async (workerId: string) => {
  // console.log("导出一个工友", workerId);
  const res = await exportOneWorkerApi({ id: workerId });
  if (res) {
    let fileName = "worker.xlsx"; // 文件名
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel"
    });
    console.log("blobblobblob", blob);
    let elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.target = "_blank";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL对象
    document.body.removeChild(elink);
  }
};

const handleChat = row => {
  router.push({
    path: "/im/index",
    query: {
      userId: row.userId
    }
  });
};

// 加载当前机构的分组信息
onMounted(() => {
  getCompanyGrups();
});

// 打开 dialog(新增、查看、编辑)
const dialogRef = ref();
const handleOpenDialog = (optType: OptEnum, rowData?: { id: string }) => {
  let params = {
    optType: optType,
    rowData: { ...rowData, id: rowData.workerId }
  };
  dialogRef.value.acceptParams(params);
};

// 打开分组
const wgdialogRef = ref();
const handleOpenWorkGroupDialog = (optType: OptEnum, workerId: string) => {
  let params = {
    optType: optType,
    workerId
  };
  wgdialogRef.value.acceptParams(params);
};

const wmdialogRef = ref();
const handleOpenWorkMarkerDialog = (optType: OptEnum, id: string) => {
  let params = {
    optType: optType,
    id
  };
  wmdialogRef.value.acceptParams(params);
};
</script>

<style scoped lang="scss">
.select-box {
  padding: 0 20px;
  margin-bottom: 10px;
}

.left-box {
  height: 60px;
  width: 60px;
  border-radius: 50%;
  // border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  position: relative;

  img {
    height: 60px;
    width: 60px;
  }
}

.info-item {
  display: flex;
  font-size: 0.8em;
  font-weight: 600;
  overflow: hidden;

  .title-info {
    color: var(--el-color-info);
    font-weight: 300;
  }

  & .el-tag {
    margin-right: 0.5rem;
  }

  .info-b {
    font-weight: 600;
    font-size: 1rem;
    color: var(--el-color-info);
    margin-bottom: 5px;
  }

  .info-s {
    font-size: 0.8rem;
    color: var(--el-color-info);
  }

  .info-info {
    margin: 0 5px;
  }
}

.apply-wrapper {
  // border: 1px solid red;
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;

  .job-title {
    width: 100%;
    margin-bottom: 10px;
    font-size: 1.1rem;
    font-weight: 600;
    // border: 1px solid red;
    // display: flex;
    // & .el-tag {
    //   margin-right: 0.5rem;
    // }
  }
  .job-date {
    display: flex;
    align-items: center;
    // flex-direction: row-reverse;

    .job-data-title {
      font-size: 0.8rem;
      font-weight: 600;
      color: var(--el-color-info-light-5);
    }

    .job-data-info {
      font-size: 0.9rem;
      color: var(--el-color-info);
      font-weight: 600;
    }
  }
}

.phone-info {
  margin: 0 5px;
  font-weight: 600;
}

.ml-2 {
  margin: 0 10px;
  font-size: 0.8rem;
}

.mt-10 {
  margin: 3px 0px;
}

.worker-exp-wrapper {
  margin-bottom: 3px;
}

.info-identity {
  border: 1px solid green;
  border-radius: 4px;
  padding: 0;
  .phone-identity {
    padding: 0;
    margin: 0 5px;
  }
}

.marker-dot {
  transform: translateX(30px);
}

.work-tag-wrapper {
  // border: 1px solid red;
  height: 60px;
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;

  .tag-bar {
    width: 100%;
    margin-bottom: 5px;
    display: flex;
    & .el-tag {
      margin-right: 0.5rem;
    }
  }
}

.flagsee-wrapper {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // border: 1px solid red;
}

.expjob-wrapper {
  width: 100%;
  height: 60px;
  // border: 1px solid red;
}
</style>
